package com.yeyks.rocketmq.service.customer;

import cn.hutool.json.JSONUtil;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.yeyks.common.dto.mq.RefundNoticeMessage;
import com.yeyks.common.em.WebSocketTypeEnum;
import com.yeyks.commonReference.append.rocketmq.pojo.RocketMQWebsocketBasePojo;
import com.yeyks.commonReference.service.hotel.HotelInfoService;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.hotel.dal.domain.HotelInfo;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.websocket.SendMessageBean;
import com.yeyks.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author fuchangshuai
 * @date 2019/08/09 16:06
 */
@Slf4j
@Component
public class WebSocketOrderRefundListener implements MessageListener {

    @Autowired
    private WebSocket webSocket;
    @Autowired
    private OrderHeadService orderHeadService;
    @Autowired
    private HotelInfoService hotelInfoService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            Long startTime = System.currentTimeMillis();
            byte[] body = message.getBody();
            String msg = new String(body);
            //处理业务逻辑
            disposeLogic(msg);
            log.info("webSocket检测订单退款：监听到的消息：message = {}", msg);
            Long endTime = System.currentTimeMillis();
            log.info("webSocket检测订单退款：单次消费耗时：" + (endTime - startTime) / 1000);
        } catch (Exception e) {
            log.error("MessageListener.consume error:" + e.getMessage(), e);
        }
        return Action.CommitMessage;
    }

    /**
     * c端订单退款，处理业务逻辑
     *
     * @param msg 监听到的信息
     */
    private void disposeLogic(String msg) {
        try {
            RefundNoticeMessage refundNoticeMessage = JSONUtil.toBean(msg, RefundNoticeMessage.class);
            if (null != refundNoticeMessage) {
                OrderHead orderHead = orderHeadService.getByOrderNo(refundNoticeMessage.getOrderNo());
                if (null != orderHead) {
                    HotelInfo hotelInfo = hotelInfoService.getById(orderHead.getHotelId());
                    if (null != hotelInfo) {
                        webSocket.sendMessageToUser(hotelInfo.getOperatorId(), SendMessageBean.getOrderRefundMsg());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("webSocket检测订单退款：处理监听消息异常：msg = {}", msg);
        }
    }
}
